package cdu.notFound.controller;
import cdu.notFound.model.User;
import cdu.notFound.service.UserService;
import cdu.notFound.service.impl.UserServiceImpl;
import cdu.notFound.utils.MD5;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 注册
 */
public class RegisterServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}
	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		//获取参数
		String email = request.getParameter("input_email");
		String pwd = request.getParameter("input_password1");
		String pwd2 = request.getParameter("input_password2");
		//若没填写名字就叫某用户
		String name= (request.getParameter("name")==null && request.getParameter("name").length()!=0)?"某用户":request.getParameter("name");
		User user = new User();
		boolean isRegister = false;//是否注册成功
		String isPwdSame="";//密码是否相等
		String isPwd="";//是否符合密码
		String isEmail="";//是否符合邮箱
		UserService userService = new UserServiceImpl();
		//正则表达式判断邮箱，密码是否规范
		if (email.matches("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$")
				&& ((userService.findByEmail(email)) == null)) {
			if (pwd.matches("[A-Za-z0-9_]{6,}")) {
				if (pwd2.equals(pwd)) {
					pwd = MD5.getMD5(MD5.getMD5(pwd));
					user.setEmail(email);
					user.setPwd(pwd);
					user.setName(name);
					if (userService.register(user)) {
						isRegister = true;//注册成功
					}
					request.setAttribute("isRegister", isRegister);
					if (isRegister) {//成功就跳转到登录页面
						request.getRequestDispatcher("/user/login.jsp")
								.forward(request, response);
					} else {
						request.getRequestDispatcher("/user/register.jsp")
								.forward(request, response);
					}
				} else {
					isPwdSame="两次密码不相同";
				}
			} else {
				isPwd="密码格式错误";
			}
		} else {
			isEmail="邮箱格式错误或已经存在";
		}
		if(isRegister == true){
			request.setAttribute("isRegister",isRegister);
			request.getRequestDispatcher("/user/login.jsp").forward(request, response);
		}else{
			request.setAttribute("isRegister",false);
			request.setAttribute("isPwdSame",isPwdSame);
			request.setAttribute("isPwd",isPwd);
			request.setAttribute("isEmail",isEmail);
			request.getRequestDispatcher("/user/register.jsp").forward(request, response);
		}
	}

}
